package com.bw.finance.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.finance.conf.ResponseResult;
import com.bw.finance.eneity.EduCourse;
import com.bw.finance.eneity.es.BorrowBiao;
import com.bw.finance.eneity.es.res.SelType;
import com.bw.finance.repository.EduCourseRepository;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/educourse")
public class EduController {

    @Autowired
    private EduCourseRepository eduCourseRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @PostMapping("/findall/{pagenum}/{pagesize}")
    public ResponseResult findall(@PathVariable Integer pagenum, @PathVariable Integer pagesize, @RequestBody SelType selType){
        ResponseResult result = ResponseResult.SUCCESS();
        try{
            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
            if(selType.getRepayType()!=null){
                queryBuilder.must(QueryBuilders.termQuery("repayType",selType.getRepayType()));
            }
            if(selType.getInterhou()!=null&&selType.getInterqian()!=null){
                queryBuilder.must(QueryBuilders.rangeQuery("interest").gte(selType.getInterqian()));
                queryBuilder.must(QueryBuilders.rangeQuery("interest").lte(selType.getInterhou()));
            }
            if(selType.getInterhou()==null&&selType.getInterqian()!=null){
                queryBuilder.must(QueryBuilders.rangeQuery("interest").gte(selType.getInterqian()));
            }
            if(selType.getTremType()!=null&&selType.getTremqian()!=null&&selType.getTremhou()!=null){
                if(selType.getTremType()==0){
                    queryBuilder.must(QueryBuilders.termQuery("tremType",0));
                    queryBuilder.must(QueryBuilders.rangeQuery("trem").gte(selType.getTremqian()));
                    queryBuilder.must(QueryBuilders.rangeQuery("trem").lte(selType.getTremhou()));
                }
                if(selType.getTremType()==1){
                    queryBuilder.must(QueryBuilders.termQuery("tremType",1));
                    queryBuilder.must(QueryBuilders.rangeQuery("trem").gte(selType.getTremqian()));
                    queryBuilder.must(QueryBuilders.rangeQuery("trem").lte(selType.getTremhou()));
                }
            }
            if(selType.getBidType()!=null){
                queryBuilder.must(QueryBuilders.termQuery("bidType",selType.getBidType()));
            }
            if(selType.getBidName()!=null&&selType.getBidName()!=""){
                queryBuilder.must(QueryBuilders.matchQuery("bidName",selType.getBidName()));
            }

            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("bidName");
            highlightBuilder.preTags("<span style=\"color:red;\">");
            highlightBuilder.postTags("</span>");

            NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
            Pageable pageable= PageRequest.of(pagenum,pagesize);
            searchQueryBuilder.withPageable(pageable);
            searchQueryBuilder.withQuery(queryBuilder);
            searchQueryBuilder.withHighlightBuilder(highlightBuilder);
            System.out.println(JSON.toJSONString(elasticsearchRestTemplate.queryForPage(searchQueryBuilder.build(), BorrowBiao.class)));
            result.setResult(elasticsearchRestTemplate.queryForPage(searchQueryBuilder.build(), BorrowBiao.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    List<BorrowBiao> list = new ArrayList<>();//结果集合
                    for (SearchHit searchhit : searchResponse.getHits()) {//查询结果
                        BorrowBiao borrowBiao = JSONObject.parseObject(searchhit.getSourceAsString(), BorrowBiao.class);
                        Map<String, HighlightField> highlightFields = searchhit.getHighlightFields();//被高亮的字段
                        HighlightField highlightField = highlightFields.get("bidName");
                        if (highlightField != null) {
                            Text[] fragments = highlightField.fragments();
                            String frmString = fragments[0].string();
                            borrowBiao.setBidName(frmString);
                        }
                        list.add(borrowBiao);
                    }
                    if (list.size() > 0) {
                        return new AggregatedPageImpl<T>((List<T>) list,pageable,searchResponse.getHits().getTotalHits());
                    }
                    return null;
                }
                @Override
                public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                    return null;
                }
            }));
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败");
        }
        return result;
    }

    @GetMapping("/findtext/{pagenum}/{pagesize}")
    public Page<BorrowBiao> findtext(@PathVariable Integer pagenum, @PathVariable Integer pagesize){
            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
            /*queryBuilder.must(QueryBuilders.termQuery("repayType","0"));
            queryBuilder.must(QueryBuilders.rangeQuery("interest").gte(2));
            queryBuilder.must(QueryBuilders.rangeQuery("interest").lte(15));*/
            queryBuilder.must(QueryBuilders.matchQuery("bidName","女士"));

            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("bidName");
            highlightBuilder.preTags("<span style=\"color:red\">");
            highlightBuilder.postTags("</span>");

            NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();
            Pageable pageable= PageRequest.of(pagenum,pagesize);
            searchQueryBuilder.withPageable(pageable);
            searchQueryBuilder.withQuery(queryBuilder);
            searchQueryBuilder.withHighlightBuilder(highlightBuilder);

            return elasticsearchRestTemplate.queryForPage(searchQueryBuilder.build(), BorrowBiao.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {//定制查询结果
                    List<BorrowBiao> list = new ArrayList<>();//结果集合
                    for (SearchHit searchhit : searchResponse.getHits()) {//查询结果
                        BorrowBiao borrowBiao = JSONObject.parseObject(searchhit.getSourceAsString(), BorrowBiao.class);
                        Map<String, HighlightField> highlightFields = searchhit.getHighlightFields();//被高亮的字段
                        HighlightField highlightField = highlightFields.get("bidName");
                        if (highlightField != null) {
                            Text[] fragments = highlightField.fragments();
                            String frmString = fragments[0].string();
                            borrowBiao.setBidName(frmString);
                        }
                        list.add(borrowBiao);
                    }
                    if (list.size() > 0) {
                        return new AggregatedPageImpl<T>((List<T>) list);
                    }
                    return null;
                }

                @Override
                public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                    return null;
                }
            });
    }

    @PostMapping("/save")
    public void save(@RequestBody BorrowBiao borrowBiao){
        eduCourseRepository.save(borrowBiao);
    }

    @PostMapping("/del")
    public void del(@RequestBody BorrowBiao borrowBiao){
        eduCourseRepository.deleteById(borrowBiao.getId());
    }

    @GetMapping("/savetext")
    public void savetext(){
        BorrowBiao borrowBiao = new BorrowBiao();
        borrowBiao.setId("1");
        borrowBiao.setBidName("吴女士单独所有房产抵押贷款13万元");
        borrowBiao.setBidType(0);
        BigDecimal bigDecimal = new BigDecimal(400000);
        borrowBiao.setTotalAmount(bigDecimal);
        BigDecimal bigDecimal1 = new BigDecimal(13);
        borrowBiao.setInterest(bigDecimal1);
        borrowBiao.setTremType(0);
        borrowBiao.setTrem(10);
        borrowBiao.setRepayType(0);
        BigDecimal bigDecimal2 = new BigDecimal(0);
        borrowBiao.setRaiseAmount(bigDecimal2);
        eduCourseRepository.save(borrowBiao);
    }

}
